// 
// DotNetNuke?- http://www.dotnetnuke.com 
// Copyright (c) 2002-2011 
// by DotNetNuke Corporation 
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated 
// documentation files (the "Software"), to deal in the Software without restriction, including without limitation 
// the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and 
// to permit persons to whom the Software is furnished to do so, subject to the following conditions: 
// 
// The above copyright notice and this permission notice shall be included in all copies or substantial portions 
// of the Software. 
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
// TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL 
// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF 
// CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 
// DEALINGS IN THE SOFTWARE. 
// 

using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Collections;
using System.Collections.Generic;
using System.Reflection;

using DotNetNuke;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Security;
using DotNetNuke.Services.Exceptions;
using DotNetNuke.Services.Localization;
using DotNetNuke.Entities.Modules;
using DotNetNuke.Entities.Modules.Actions;

using CharityGamesOnline.Modules.Game;
using CharityGamesOnline.Modules.Common;

namespace CharityGamesOnline.Modules.Game.Trivia
{

    /// ----------------------------------------------------------------------------- 
    /// <summary> 
    /// The ViewTrivia class displays the content 
    /// </summary> 
    /// <remarks> 
    /// </remarks> 
    /// <history> 
    /// </history> 
    /// ----------------------------------------------------------------------------- 
    partial class ViewTrivia : CGOBase, ICharityGameClient
    {
        private int gameEnrollmentID;
        private const string webServiceFormat = "http://{0}/{1}/{2}";
        private const string defaultWebServiceFile = "Trivia.asmx";
        private WebService.Trivia wsTrivia = new CharityGamesOnline.Modules.Game.Trivia.WebService.Trivia();
        

        public int GameEnrollmentID
        {
            get
            {
                if (gameEnrollmentID == 0)
                {
                    if ((Request.QueryString["GameEnrollmentID"] != null))
                    {
                        gameEnrollmentID = Int32.Parse(Request.QueryString["GameEnrollmentID"]);
                    }
                }
                return gameEnrollmentID;
            }
        }

        private string TriviaWebServiceUrl
        {
            get
            {
                if (!Null.IsNull(Settings["TriviaWebServiceUrl"]))
                {
                    return string.Format(webServiceFormat, PortalAlias.HTTPAlias, ControlPath, Settings["TriviaWebServiceUrl"].ToString());
                }
                else
                    return string.Format(webServiceFormat, PortalAlias.HTTPAlias, ControlPath, defaultWebServiceFile);
            }
        }

        #region "Event Handlers"

        /// ----------------------------------------------------------------------------- 
        /// <summary> 
        /// Page_Load runs when the control is loaded 
        /// </summary> 
        /// ----------------------------------------------------------------------------- 
        protected void Page_Load(object sender, System.EventArgs e)
        {
            try
            {
                wsTrivia.Url = TriviaWebServiceUrl;
                imgTrue.Visible = false;
                imgFalse.Visible = false;
                if (!Page.IsPostBack)
                {
                    divQuestion.Visible = false;
                    divButtons.Visible = false;
                    divStart.Visible = true;
                }
            }

            catch (Exception exc)
            {
                //Module failed to load 
                Exceptions.ProcessModuleLoadException(this, exc);
            }
        }        

        protected void btnStart_Click(object sender, EventArgs e)
        {
            int gameCount = wsTrivia.StartGame(PortalId, GameEnrollmentID, UserId);
            if (gameCount > 0)
            {
                WebService.TriviaResultSummaryInfo objSummary = wsTrivia.GetResultSummary(PortalId, GameEnrollmentID, UserId);

                lbQuestionCount.Text = (objSummary.TotalCount - objSummary.DeprecatedCount).ToString();

                if (PopulateQuestion())
                {
                    RefreshSummary();
                    divQuestion.Visible = true;
                    divButtons.Visible = true;
                    divStart.Visible = false;
                    btnSubmit.Enabled = false;
                    btnNextQuestion.Enabled = false;
                    btnSendAnswer.Enabled = true;
                }
            }
        }

        protected void btnNextQuestion_Click(object sender, EventArgs e)
        {
            if (PopulateQuestion())
            {
                btnSubmit.Enabled = false;
                btnNextQuestion.Enabled = false;
                btnSendAnswer.Enabled = true;
                imgTrue.Visible = false;
                imgFalse.Visible = false;                                
                rblAnswer.Enabled = true;
            }
            else
            {
                btnSubmit.Enabled = true;
                btnNextQuestion.Enabled = false;
                btnSendAnswer.Enabled = false;
                lbMessage.Text = "You have completed all questionis, please click Submit button to end the game";
            }
        }

        protected void btnSendAnswer_Click(object sender, EventArgs e)
        {
            int userAnswerID = Int32.Parse(rblAnswer.SelectedValue);
            //lbMessage.Text = string.Format("You selection is [{0}]{1}", rblAnswer.SelectedValue, rblAnswer.SelectedItem.Text);
            int correctAnswerID = wsTrivia.SendAnswer(PortalId, GameEnrollmentID, UserId, Int32.Parse(lbQuestionIndex.Text), userAnswerID, 100, 100);
            if (userAnswerID == correctAnswerID)
            {
                imgTrue.Visible = true;                
            }
            else
            {
                imgFalse.Visible = true;                
            }
            ListItem correctAnswer = rblAnswer.Items.FindByValue(correctAnswerID.ToString());
            if (correctAnswer != null)
            {
                correctAnswer.Text = string.Format("<b>{0}</b>", correctAnswer.Text);
            }
            rblAnswer.Enabled = false;
            btnNextQuestion.Enabled = true;
            btnSendAnswer.Enabled = false;
            rowComment.Visible = false;
            RefreshSummary();
        }

        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            int intEnd = wsTrivia.EndGame(PortalId, GameEnrollmentID, UserId);
            if (intEnd > 0)
            {
                int playedTimes = wsTrivia.GetPlayedCount(PortalId, GameEnrollmentID);
                int userRank = wsTrivia.GetUserRank(PortalId, GameEnrollmentID, UserId);
                lbMessage.Text = string.Format("Your rank is {0}/{1}", userRank, playedTimes);
                btnSubmit.Enabled = false;
            }
        }        
        #endregion        

        private bool PopulateQuestion()
        {
            bool retVal = false;
            WebService.TriviaQuestionInfo objQuestion = wsTrivia.GetQuestion(PortalId, GameEnrollmentID, UserId);
            if (objQuestion != null)
            {
                retVal = true;
                lbQuestionID.Text = objQuestion.QuestionID.ToString();
                lbQuestionIndex.Text = objQuestion.QuestionIndex.ToString();
                lbDifficulty.Text = objQuestion.Difficulty.ToString();
                lbCategory.Text = objQuestion.CategoryName;
                lbQuestion.Text = objQuestion.Description;
                lbComment.Text = objQuestion.Comment;                
                rowComment.Visible = false;

                WebService.TriviaAnswerInfo[] lstAnswer = wsTrivia.GetAnswers(PortalId, GameEnrollmentID, UserId, objQuestion.QuestionIndex);
                if (lstAnswer.Length != 0)
                {
                    rblAnswer.DataSource = lstAnswer;
                    rblAnswer.DataBind();
                }
            }

            return retVal;
        }

        private void RefreshSummary()
        {
            WebService.TriviaResultSummaryInfo objSummary = wsTrivia.GetResultSummary(PortalId, GameEnrollmentID, UserId);
            if (objSummary != null)
            {
                lbTotal.Text = objSummary.TotalCount.ToString();
                lbDeprecated.Text = objSummary.DeprecatedCount.ToString();
                lbCorrect.Text = objSummary.CorrectCount.ToString();
                lbWrong.Text = objSummary.WrongCount.ToString();
                lbLeft.Text = objSummary.UndoCount.ToString();

                lbScore.Text = wsTrivia.GetScore(PortalId, GameEnrollmentID, UserId).ToString();
            }
        }
    }

}